//
//  JQFYMyShowController.m
//  JQFY
//
//  Created by 代辉 on 2017/8/23.
//  Copyright © 2017年 yannis. All rights reserved.
//

#import "JQFYMyShowController.h"
#import "JQFYMyShowCell.h"
#import "JQFYCheckTikectView.h"
#import "JQFYMyshowListModel.h"

@interface JQFYMyShowController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) ZJAnimationPopView *alert;
@property (nonatomic,strong) NSArray *myshowList;
@property (nonatomic,strong) JQFYCheckTikectView *checkTikect;
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,strong) JQFYMyshowListModel *listModel;
@property (nonatomic,copy) NSString *orderID;
@end

static NSString *myShowCell = @"myShowCell";

@implementation JQFYMyShowController

- (UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [UITableView new];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
    }

    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self setupUI];
    [self loadData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySucess) name:@"paySucess" object:nil];
}
// 微信支付成功后刷新
- (void)paySucess
{
    [self loadData];
}
- (void)setupUI
{
    self.navigationItem.title = @"我的票务";
    UIImage *bgImage = [UIImage imageNamed:@"frame_top@2x(1)"];
    UIImageView *topBgImageView = [[UIImageView alloc] initWithImage:bgImage];
    [self.view addSubview:topBgImageView];
    
    [topBgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.right.equalTo(self.view);
    }];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topBgImageView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    
    [self.tableView registerClass:[JQFYMyShowCell class] forCellReuseIdentifier:myShowCell];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 64 *SCAL;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 52 *SCAL, 0);
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(aleartCheckTikectNoification:) name:AleartCheckTikectNoification object:nil];
    self.listModel = [JQFYMyshowListModel new];
}
- (void)loadData
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [self.listModel getMyshowList:^(NSArray *list) {
        [hud hide:YES];
        self.myshowList = list;
        [self.tableView reloadData];
    } file:^(NSError *error) {
        hud.detailsLabelText = @"网络加载失败";
        [hud hide:YES afterDelay:2];
    }];
}


/**
 验证二维码

 @param orderID  订单号
 @param success  成功回调二维码地址
 */
- (void)verificationQRcode:(NSString *)orderID success:(void(^)(NSString *orderID,NSInteger status))success
{
    [self.listModel verificationQRcode:^(NSString *orderID,NSInteger status){
        
        success(orderID,status);
        if (status == 1) {
            dispatch_async(dispatch_get_main_queue(), ^{
            
                self.checkTikect.status = status;
                [self.timer invalidate];
            });
        }
        
    } file:^{
        [MBProgressHUD showWithMessage:@"网络请求失败"];
    } orderID:orderID];
}
#pragma mark - AleartCheckTikectNoification -
- (void)aleartCheckTikectNoification:(NSNotification *)noti
{
    NSUInteger num = [noti.object integerValue];
    if (num == 1) {
        NSString *orderID = noti.userInfo[OrderID];
        
        self.checkTikect = [[JQFYCheckTikectView alloc] initWithFrame:self.view.bounds];
        
        [self verificationQRcode:orderID success:^(NSString *order,NSInteger status) {
            self.checkTikect.orderID = order;
            self.orderID = orderID;
            [self staterTimer];

        }];
        self.alert = [[ZJAnimationPopView alloc] initWithCustomView:self.checkTikect popStyle:ZJAnimationPopStyleScale dismissStyle:ZJAnimationDismissStyleScale];
        self.alert.popBGAlpha = 0.8;
        [self.alert pop];
    } else {
        [self.alert dismiss];
        [self.timer invalidate];
    }
}
- (void)staterTimer
{
    self.timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(examineQRcode) userInfo:nil repeats:YES];
    
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)examineQRcode {
    
    [self.listModel verificationQRcode:^(NSString *qrCode, NSInteger status) {
    
        if (status == 1) {
            [self.timer invalidate];
            self.checkTikect.status = 1;
        }
    } file:^{
        [MBProgressHUD showWithMessage:@"网络错误"];
    } orderID:self.orderID];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.myshowList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JQFYMyShowCell *cell = [tableView dequeueReusableCellWithIdentifier:myShowCell forIndexPath:indexPath];
    cell.model = self.myshowList[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    JQFYMyshowListModel *model = self.myshowList[indexPath.row];
    if ([model.pay_status integerValue] == 0) {
        
        NSDictionary *dict = @{
                               @"token":[JQFYUserData userDataInSandbox].token,
                               @"out_trade_no":model.out_trade_no
                               };
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择支付方式" preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *wxPay = [UIAlertAction actionWithTitle:@"微信" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isPop"];
            [__Pay__ wxPay:dict];
        }];
        
        UIAlertAction *aliPay = [UIAlertAction actionWithTitle:@"支付宝" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [__Pay__ aliPay:dict success:^{
                [MBProgressHUD showWithMessage:@"支付成功"];
                [self loadData];
            }];
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:aliPay];
        [alert addAction:wxPay];
        [alert addAction:cancel];

        [self presentViewController:alert animated:YES completion:nil];

    }
}

- (void)dealloc
{
    [self.timer invalidate];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
